package com.lzxuni.modules.oss;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.lzxuni.config.OssClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author:孙志强
 * @create:2019-01-22 10:35
 * @Modified BY:
 **/
@RestController
public class OssController {

	@Autowired
	private OssClientFactory ossClientFactory;
	/**
	 * OSS签名授权
	 */
	@RequestMapping("/osssignuature")
	public void authorize(HttpServletRequest request, HttpServletResponse response) {
		String dir = "user-dir";
		if(null!= request.getParameter("dir")){
			dir = request.getParameter("dir");
		}
		String host = "http://" + ossClientFactory.getBucketName() + "." + ossClientFactory.getEndpoint();
		OSSClient client = ossClientFactory.getOSSClient();
		try {
			long expireTime = 3000;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);
			client.shutdown();

			Map<String, Object> respMap = new LinkedHashMap<>();
			respMap.put("accessid", ossClientFactory.getAccessKeyId());
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			respMap.put("dir", dir);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			JSONObject ja1 = new JSONObject(respMap);
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "GET, POST");
			response(request, response, ja1.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void response(HttpServletRequest request, HttpServletResponse response, String results) throws IOException {
		String callbackFunName = request.getParameter("callback");
		if (callbackFunName==null || callbackFunName.equalsIgnoreCase(""))
			response.getWriter().println(results);
		else
			response.getWriter().println(callbackFunName + "( "+results+" )");
		response.setStatus(HttpServletResponse.SC_OK);
		response.flushBuffer();
	}

}
